<?php
namespace Base\Controller;

use Admin\Model\UserModel;
use Think\Controller;

class BaseHomeController extends Controller
{
    public $user;

    protected $relation;//关联
    protected $upload;//是否有上传字段
    protected $uploadConfig;//上传参数配置

    public function __construct($relation = true, $upload = false, $uploadConfig = array(
        'input_name' => 'coverFile',//文本框name
        'save_path' => 'cover',//保存路径
        'data_field' => 'cover'//数据库字段
    ))
    {
        parent::__construct();
        $this->relation = $relation;
        $this->upload = $upload;
        $this->uploadConfig = $uploadConfig;

        if (isMobile()) {
            C('DEFAULT_THEME', 'Default/Html/Mobile');
        }

        $uid = $this->isLogin();

        if ($uid) {
            $select_user = (new UserModel())->where(array(
                'status' => 1
            ))->relation(true)->find((int)$uid);
            if (!empty($select_user)) {
                $this->user = $select_user;
                $this->assign('user', $this->user);
            } else {
                session('user_id', null);
                $this->showLogin();
            }
        }

        //保存backurl
        $this->createBackUrl();
    }

    /**
     * 跳转到登录页面
     */
    public function showLogin()
    {
        if (strtolower(CONTROLLER_NAME) != 'index') {
            $this->redirect('User/login');
        }
    }

    /**
     * 是否登录
     * */
    public function isLogin()
    {
        return session('user_id') ? session('user_id') : false;
    }

    /**
     * 需要登录
     * @param string $msg
     */
    protected function hasLogin($msg = '')
    {
        if (!$this->isLogin()) {
            if ($msg) {
                $this->error($msg, U('User/login'));
            } else {
                $this->showLogin();
            }
        }
    }

    /**
     * 进入用户中心
     */
    protected function showUserCenter()
    {
        $this->redirect('User/data');
    }


    /**
     * 生成backurl
     * @return string
     */
    protected function createBackUrl()
    {
        $no_back_action = array('buy', 'showadd');
        if (!I('get.id') || in_array(strtolower(ACTION_NAME), $no_back_action)) {
            return;
        }
        $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER["REQUEST_URI"];
        session('back_url_wsw', $url);
    }

    /**
     * 获取backurl
     * @return mixed
     */
    protected function getBackUrl()
    {
        $url = session('back_url_wsw');
        return $url;
    }
}